<?php

namespace App\Http\Controllers;

use App\Http\Requests\addBankCardRequest;
use App\Http\Requests\ExportRequest;
use App\Http\Requests\RechargeRequest;
use App\Http\Requests\WithdrawRequest;
use App\Http\Resources\ImportExportCollection;
use App\Http\Resources\RechargeShowResource;
use App\Http\Resources\RechargeWithdrawCollection;
use App\Http\Resources\ShowResource;
use App\Http\Resources\WithdrawShowResource;
use App\Model\Account;
use App\Model\BankCard;
use App\Model\ImportExport;
use App\Model\RechargeWithdraw;
use App\Traits\Password;
use DB;
use Exception;

class FinanceController extends Controller
{
    use Password;

    /**
     * 充值
     *
     * @param RechargeRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function rechargeStore(RechargeRequest $request)
    {
        $user = request()->user();
        // 判断是否有未完成订单
        $recharge = RechargeWithdraw::where('user_id', $user->id)
            ->where('type', 0)
            ->where('status', 0)
            ->first();
        if ($recharge) {
            return response()->json(['error' => '有未完成充值订单，不可充值'], 403);
        }

        $rechargeWithdraw               = new RechargeWithdraw();
        $rechargeWithdraw->user_id      = $user->id;
        $rechargeWithdraw->number       = $request->input('number');
        $rechargeWithdraw->bank_card_id = $request->input('bank_card_id');
        $rechargeWithdraw->type         = 0;

        if (! $rechargeWithdraw->save()) {
            return response()->json(['error' => '网络异常，请重试'], 500);
        }

        return response()->json(['您的订单号' => $rechargeWithdraw->id], 200);
    }

    /**
     * 充值详情
     *
     * @param $id
     * @return RechargeShowResource|\Illuminate\Http\JsonResponse
     */
    public function rechargeShow($id)
    {
        $recharge = RechargeWithdraw::select(['id', 'number', 'bank_card_id', 'type', 'status', 'created_at'])
            ->where('id', $id)
            ->where('user_id', request()->user()->id)
            ->where('type', 0)
            ->first();

        if (! $recharge) {
            return response()->json(['error' => '没有充值订单', 404]);
        }

        return new RechargeShowResource($recharge);
    }

    /**
     * 充值记录
     *
     * @return RechargeWithdrawCollection|\Illuminate\Http\JsonResponse
     */
    public function rechargeIndex()
    {
        $record = RechargeWithdraw::select(['id', 'number', 'status', 'created_at'])
            ->where('user_id', request()->user()->id)
            ->where('type', 0)
            ->orderBy('created_at', 'desc')
            ->paginate();

        if (! $record->total()) {
            return response()->json(['error' => '没有充值记录', 404]);
        }

        return new RechargeWithdrawCollection($record);
    }

    /**
     * 充值撤销
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function rechargeDestroy($id)
    {
        $recharge = RechargeWithdraw::where('id', $id)
            ->where('user_id', request()->user()->id)
            ->where('type', 0)
            ->where('status', 0)
            ->first();

        if (! $recharge) {
            return response()->json(['error' => '订单不存在', 404]);
        }

        if (! $recharge->delete()) {
            return response()->json(['error' => '网络错误，请重试', 500]);
        }

        return response()->json(['message' => '撤销成功'], 200);
    }

    /**
     * 提现
     *
     * @param WithdrawRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function withdrawsStore(WithdrawRequest $request)
    {
        $user = request()->user();
        //判断银行卡存在
        $bankCard = BankCard::where('id', $request->input('bank_card_id'))
            ->where('user_id', $user->id)
            ->first();
        if (! $bankCard) {
            return response()->json(['error' => '非法操作', 403]);
        }

        // 判断交易密码
        $this->checkPayPassword($user, $request->input('pay_password'));

        // 判断可用余额是否充足
        $rmbAccount = Account::where('user_id', $user->id)
            ->where('coin_id', 0)
            ->first();

        if ($request->input('number') > $rmbAccount->available) {
            return response()->json(['error' => '余额不足', 403]);
        }

        // 手续费，不足2按2算
        $fee                    = $request->input('number') * 0.005 > 2 ? $request->input('number') * 0.005 : 2;
        $withdraw               = new RechargeWithdraw();
        $withdraw->user_id      = $user->id;
        $withdraw->bank_card_id = $request->input('bank_card_id');
        $withdraw->number       = $request->input('number');
        $withdraw->type         = 1;
        $withdraw->withdraw_fee = $fee;
        $rmbAccount->disable($request->input('number'));

        try {
            DB::transaction(function () use ($withdraw, $rmbAccount, $request) {
                $withdraw->save();
                // 冻结人民币可用，增加不可用
                $rmbAccount->disable($request->input('number'));
            });
        } catch (Exception $exception) {
            return response()->json(['error' => '网络异常，请重试', 500]);
        }

        return response()->json(['message' => '订单已提交，请耐心等候'], 200);
    }

    /**
     * 提现详情
     *
     * @param $id
     * @return WithdrawShowResource|\Illuminate\Http\JsonResponse
     */
    public function withdrawsShow($id)
    {
        $withdraw = RechargeWithdraw::select(['id', 'number', 'bank_card_id', 'type', 'status', 'created_at'])
            ->where('user_id', request()->user()->id)
            ->where('id', $id)
            ->where('type', 1)
            ->first();

        if (! $withdraw) {
            return response()->json(['error' => '提现订单不存在'], 404);
        }

        return new WithdrawShowResource($withdraw);
    }

    /**
     * 提现记录
     *
     * @return RechargeWithdrawCollection|\Illuminate\Http\JsonResponse
     */
    public function withdrawsIndex()
    {
        $record = RechargeWithdraw::select(['id', 'status', 'number', 'created_at'])
            ->where('user_id', request()->user()->id)
            ->where('type', 1)
            ->orderBy('created_at', 'desc')
            ->paginate();

        if (! $record->total()) {
            return response()->json(['error' => '提现记录不存在'], 404);
        }

        return new RechargeWithdrawCollection($record);
    }

    //转入
    public function import()
    {
    }

    /**
     * 转入记录
     *
     * @param $coinId
     * @return ImportExportCollection|\Illuminate\Http\JsonResponse
     */
    public function importRecord($coinId)
    {
        $import = ImportExport::select('id', 'number', 'status', 'type', 'created_at')
            ->where('user_id', request()->user()->id)
            ->where('coin_id', $coinId)
            ->where('type', 0)
            ->orderBy('created_at', 'desc')
            ->paginate();

        if (!$import->total()) {
            return response()->json(['error' => '没有转入记录', 404]);
        }

        return new ImportExportCollection($import);
    }

    // 虚拟币转出
    public function export(ExportRequest $request)
    {
        $user = request()->user();
        // 判断交易密码
        $this->checkPayPassword($user, $request->input('pay_password'));

        // 判断虚拟币是否充足
        $coinAccount = Account::where('coin_id', $request->input('coin_id'))
            ->where('user_id', $user->id)
            ->first();
        if ($coinAccount->available < $request->input('number')) {
            return response()->json(['error' => '虚拟币不足', 403]);
        }

        //TODO 判断转出地址是否合法

        $export                 = new ImportExport();
        $export->user_id        = $user->id;
        $export->coin_id        = $request->input('coin_id');
        $export->wallet_address = $request->input('address');
        $export->number         = $request->input('number');
        $export->fee            = $request->input('number') * 0.001;
        $export->type           = 1;

        try {
            DB::transaction(function () use ($coinAccount, $request, $export) {
                $export->save();
                $coinAccount->disable($request->input('number'));
            });
        } catch (Exception $exception) {
            return response()->json(['error' => '网络异常请重试', 500]);
        }

        return response()->json(['message' => '申请成功，请耐心等待'], 200);
    }

    /**
     * 转出记录
     *
     * @param $coinId
     * @return ImportExportCollection|\Illuminate\Http\JsonResponse
     */
    public function exportRecord($coinId)
    {
        $import = ImportExport::select('id', 'number', 'status', 'type', 'created_at')
            ->where('user_id', request()->user()->id)
            ->where('coin_id', $coinId)
            ->where('type', 1)
            ->orderBy('created_at', 'desc')
            ->paginate();

        if (! $import->total()) {
            return response()->json(['error' => '没有转出记录'], 404);
        }

        return new ImportExportCollection($import);
    }

    // 虚拟币转入、转出详情
    public function Show($id)
    {
        $export = ImportExport::select(['id', 'number', 'created_at', 'status', 'wallet_address'])
            ->where('id', $id)
            ->where('user_id', request()->user()->id)
            ->first();

        if (! $export) {
            return response()->json(['error' => '没有订单'], 404);
        }

        return new ShowResource($export);
    }

    /**
     * 添加银行卡
     *
     * @param addBankCardRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bankcardsStore(addBankCardRequest $request)
    {
        $user = request()->user();
        // 判断交易密码正确
        $this->checkPayPassword($user, $request->input('pay_password'));

        // 银行卡数量限制
        if (BankCard::where('user_id', $user->id)->count() >= 10) {
            return response()->json(['error' => '银行卡数量已达上限'], 403);
        }

        $banCard            = new BankCard();
        $banCard->user_id   = $user->id;
        $banCard->name      = $request->input('name');
        $banCard->bank_name = $request->input('bank_name');
        $banCard->province  = $request->input('province');
        $banCard->city      = $request->input('city');
        $banCard->branch    = $request->input('branch');
        $banCard->number    = $request->input('number');
        if (! $banCard->save()) {
            return response()->json(['error' => '网络错误，请重试'], 500);
        }

        return response()->json(['message' => '添加成功'], 200);
    }

    /**
     * 删除银行卡
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function bankcardsDestroy($id)
    {
        $bankCard = BankCard::where('user_id', request()->user()->id)
            ->where('id', $id)
            ->first();
        if (! $bankCard) {
            return response()->json(['error' => '银行卡不存在'], 404);
        }
        if (! $bankCard->delete()) {
            return response()->json(['error' => '网络错误，请重试'], 500);
        }

        return response()->json(['message' => '删除成功'], 200);
    }
}